"use client";
import { Show } from "@refinedev/antd";
import { useParsed, useShow } from "@refinedev/core";
import { Typography, Descriptions, Tag } from "antd";
import { useEffect, useState } from "react";
import Cookies from "js-cookie";
import { getMenuList } from "@common/api/menu_action";

interface MenuItem {
  menu_id: number;
  menu_name: string;
  parent_id?: number;
  children?: MenuItem[];
}

export default function RoleShow() {
  const { id } = useParsed();
  const { queryResult } = useShow({ 
    resource: "system/role",
    id: id
  });
  const record = queryResult?.data?.data;
  const [menuNames, setMenuNames] = useState<string[]>([]);

  useEffect(() => {
    if (record?.menu_ids && record.menu_ids.length > 0) {
      fetchMenuNames(record.menu_ids);
    }
  }, [record]);

  const fetchMenuNames = async (menuIds: number[]) => {
    try {
      const result = await getMenuList() as any;
      if (result.code==200) {
        const allMenus = flattenMenus(result.data || []);
        const names = menuIds.map(id => {
          const menu = allMenus.find(m => m.menu_id === id);
          return menu ? menu.menu_name : `菜单${id}`;
        });
        setMenuNames(names);
      }
    } catch (error) {
      console.error('获取菜单名称失败:', error);
    }
  };

  const flattenMenus = (menus: MenuItem[]): MenuItem[] => {
    const result: MenuItem[] = [];
    const flatten = (items: MenuItem[]) => {
      items.forEach(item => {
        result.push(item);
        if (item.children && item.children.length > 0) {
          flatten(item.children);
        }
      });
    };
    flatten(menus);
    return result;
  };

  const getStatusText = (status: string) => {
    return status === '0' ? '正常' : '停用';
  };

  return (
    <Show>
      <Descriptions column={1} bordered size="middle">
        <Descriptions.Item label="角色ID">{record?.role_id}</Descriptions.Item>
        <Descriptions.Item label="角色名称">{record?.role_name}</Descriptions.Item>
        <Descriptions.Item label="权限字符串">{record?.role_key}</Descriptions.Item>
        <Descriptions.Item label="显示顺序">{record?.role_sort}</Descriptions.Item>
        <Descriptions.Item label="状态">
          <Tag color={record?.status === '0' ? 'green' : 'red'}>
            {getStatusText(record?.status)}
          </Tag>
        </Descriptions.Item>
        <Descriptions.Item label="菜单权限">
          {menuNames.length > 0 ? (
            <div>
              {menuNames.map((name, index) => (
                <Tag key={index} color="blue" style={{ marginBottom: '4px' }}>
                  {name}
                </Tag>
              ))}
            </div>
          ) : (
            <span style={{ color: '#999' }}>未分配菜单权限</span>
          )}
        </Descriptions.Item>
        <Descriptions.Item label="备注">{record?.remark || '-'}</Descriptions.Item>
      </Descriptions>
    </Show>
  );
} 